<template>
	<view>
		<button type="default" size="mini" class="btn" @click="sendCode" :disabled="disabled">{{ btnText }}</button>
	</view>
</template>

<script>
	import {getSendCode} from '../api/indexApi.js'
	// 验证手机号是否正确
	const regTel = (tel) => {
	    let reg = /^1[3|4|5|7|8]\d{9}$/
	    return reg.test(tel)
	}
	export default {
		data() {
			return {
				btnText: '发送验证码',
				disabled: false,
				timer: null,
				seconds: 60
			}
		},
		props: {
			phone: {
				type: Number,
				// required: true
			}
		},
		created() {
			
		},
		methods:{
			async sendCode() {
				console.log(this.phone)
				const flag = regTel(this.phone)
				if (!flag) return uni.showToast({title: '请填写正确的手机号', icon: 'none'})
				const params = {mobile: this.phone}
				const res = await getSendCode(params)
				console.log(res)
				if (res.data.code === 0) {
					uni.showToast({title: '发送成功', icon: 'none'})
					this.disabled = true
					this.timer = setInterval(() => {
						this.btnText = `${this.seconds}秒后重新发送`
						this.seconds --
						if (this.seconds == 0) {
							clearInterval(this.timer)
							this.btnText = '发送验证码'
							this.disabled = false
							this.seconds = 60
						}
					}, 1000)
				}
				
			}
		}
	}
</script>

<style scoped lang="scss">
	.btn {
		font-size: 22rpx;
		padding: 0 10rpx;
	}
</style>
